package com.l.im.common.config;

import org.yaml.snakeyaml.Yaml;

import java.io.InputStream;
import java.util.Map;

public class ConfigReader {
    private static ConfigReader instance;
    private Map<String, Object> config;

    private ConfigReader() {
        String fileName = System.getProperty("config.file", "config.yml"); // 默认 config.yml
        Yaml yaml = new Yaml();

        InputStream inputStream = getClass().getClassLoader().getResourceAsStream(fileName);

        if (inputStream != null) {
            config = yaml.load(inputStream);
        } else {
            throw new RuntimeException("YAML file not found!");
        }
    }

    public static synchronized ConfigReader getInstance() {
        if (instance == null) {
            instance = new ConfigReader();
        }
        return instance;
    }

    @SuppressWarnings("unchecked")
    private <T> T get(String path, Class<T> clazz) {
        String[] keys = path.split("\\.");
        Object value = config;

        for (String key : keys) {
            if (!(value instanceof Map)) {
                return null;
            }
            value = ((Map<String, Object>) value).get(key);
            if (value == null) return null;
        }

        if (clazz.isInstance(value)) {
            return clazz.cast(value);
        } else {
            // 可选：类型转换，比如 Integer → String，或者抛异常
//            throw new IllegalArgumentException("Config value type mismatch for path: " + path);
            return null;
        }
    }

    public <T> T getOrDefault(String path, Class<T> clazz, T defaultValue) {
        T value = get(path, clazz);
        return value != null ? value : defaultValue;
    }
}
